/**
 * Created by smzdm on 16/6/3.
 */

var rkeyEvent = /^key/,
    rmouseEvent = /^(?:mouse|contextmenu)|click/,
    rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
    rtypenamespace = /^([^.]*)(?:\.(.+)|)$/;

function returnTrue() {
    return true;
}

function returnFalse() {
    return false;
}

function safeActiveElement() {
    try {
        return document.activeElement; //返回文档中当前获取焦点的元素
    } catch (err) {}
}

/*
 * Helper functions for managing events -- not part of the public interface.
 * Props to Dean Edwards' addEvent library for many of the ideas.
 */

jQuery.event = {

    global: {},

    add: function(elem, types, handler, data, selector) {

        var handleObjIn, eventHandle, tmp,
            events, t, handleObj,
            special, handlers, type, namespaces, origType,
        //获取数据缓存
            elemData = data_priv.get(elem);

        // Don't attach events to noData or text/comment nodes (but allow plain objects)
        //检测状态，若为空数据、text或comment节点时，阻止绑定事件
        if (!elemData) {
            return;
        }

        // Caller can pass in an object of custom data in lieu of the handler
        // 一般在第一运行的时候，handler为事件处理函数,后面jQuery对handler做了一些包装
        // 检测handler是包含handler和selector的对象，包含说明handler是一个事件处理函数包
        if (handler.handler) {
            handleObjIn = handler;
            handler = handleObjIn.handler;
            selector = handleObjIn.selector;
        }

        // Make sure that the handler has a unique ID, used to find/remove it later
        //检测handler是否存在ID （guid），如果没有那么传给他一个ID
        //添加ID的目的是 用来寻找或者删除handler
        if (!handler.guid) {
            handler.guid = jQuery.guid++;
        }

        // Init the element's event structure and main handler, if this is the first
        // elemData:缓存的元素数据
        // events:事件处理程序 列队{type:[事件处理对象,事件处理对象]}
        // 检测缓存数据中没有events数据
        if (!(events = elemData.events)) {
            events = elemData.events = {};
        }

        // 如果缓存数据中没有handle数据 (此时handle为定义事件处理器)
        if (!(eventHandle = elemData.handle)) {
            eventHandle = elemData.handle = function(e) {
                // Discard the second event of a jQuery.event.trigger() and
                // when an event is called after a page has unloaded
                // typeof jQuery !== core_strundefined 检测jQuery是否被注销
                // 取消jQuery.event.trigger第二次触发事件
                // jQuery.event.dispatch 执行处理函数
                return typeof jQuery !== core_strundefined && (!e || jQuery.event.triggered !== e.type) ?
                    jQuery.event.dispatch.apply(eventHandle.elem, arguments) :
                    undefined;
            };
            // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events
            // 定义事件处理器对应的元素，用于防止IE非原生事件中的内存泄露
            eventHandle.elem = elem;
        }

        // Handle multiple events separated by a space
        // jQuery(...).bind("mouseover mouseout", fn);
        // 事件可能是通过空格键分隔的字符串，所以将其变成字符串数组
        // core_rnotwhite:/\S+/g
        types = (types || "").match(core_rnotwhite) || [""];
        // 例如：'.a .b .c'.match(/\S+/g) → [".a", ".b", ".c"]
        // 事件的个数
        t = types.length;

        while (t--) {
            // 尝试取出事件的命名空间
            // 如"mouseover.a.b" → ["mouseover.a.b", "mouseover", "a.b"]
            tmp = rtypenamespace.exec(types[t]) || [];
            // 取出事件类型，如mouseover
            type = origType = tmp[1];
            // 取出事件命名空间，如a.b，并根据"."分隔成数组
            namespaces = (tmp[2] || "").split(".").sort();

            // There *must* be a type, no attaching namespace-only handlers
            if (!type) {
                continue;
            }

            // If event changes its type, use the special event handlers for the changed type
            // 事件是否会改变当前状态，如果会则使用特殊事件
            special = jQuery.event.special[type] || {};

            // If selector defined, determine special event api type, otherwise given type
            // 根据是否已定义selector，决定使用哪个特殊事件api，如果没有非特殊事件，则用type
            type = (selector ? special.delegateType : special.bindType) || type;

            // Update special based on newly reset type
            // type状态发生改变，重新定义特殊事件
            special = jQuery.event.special[type] || {};

            // handleObj is passed to all event handlers
            // 这里把handleObj叫做事件处理对象,扩展一些来着handleObjIn的属性
            handleObj = jQuery.extend({
                type: type,
                origType: origType,
                data: data,
                handler: handler,
                guid: handler.guid,
                selector: selector,
                needsContext: selector && jQuery.expr.match.needsContext.test(selector),
                namespace: namespaces.join(".")
            }, handleObjIn);

            // Init the event handler queue if we're the first
            // 初始化事件处理列队，如果是第一次使用，将执行语句
            if (!(handlers = events[type])) {
                handlers = events[type] = [];
                handlers.delegateCount = 0;

                // Only use addEventListener if the special events handler returns false
                // 如果获取特殊事件监听方法失败，则使用addEventListener进行添加事件
                if (!special.setup || special.setup.call(elem, data, namespaces, eventHandle) === false) {
                    if (elem.addEventListener) {
                        elem.addEventListener(type, eventHandle, false);
                    }
                }
            }

            // 特殊事件使用add处理
            if (special.add) {
                special.add.call(elem, handleObj);
                // 设置事件处理函数的ID
                if (!handleObj.handler.guid) {
                    handleObj.handler.guid = handler.guid;
                }
            }

            // Add to the element's handler list, delegates in front
            // 将事件处理对象推入处理列表，姑且定义为事件处理对象包
            if (selector) {
                handlers.splice(handlers.delegateCount++, 0, handleObj);
            } else {
                handlers.push(handleObj);
            }

            // Keep track of which events have ever been used, for event optimization
            // 表示事件曾经使用过，用于事件优化
            jQuery.event.global[type] = true;
        }

        // Nullify elem to prevent memory leaks in IE
        // 设置为null避免IE中循环引用导致的内存泄露
        elem = null;
    },

    // Detach an event or set of events from an element
    remove: function(elem, types, handler, selector, mappedTypes) {

        var j, origCount, tmp,
            events, t, handleObj,
            special, handlers, type, namespaces, origType,
            elemData = data_priv.hasData(elem) && data_priv.get(elem);

        if (!elemData || !(events = elemData.events)) {
            return;
        }

        // Once for each type.namespace in types; type may be omitted
        types = (types || "").match(core_rnotwhite) || [""];
        t = types.length;
        while (t--) {
            tmp = rtypenamespace.exec(types[t]) || [];
            type = origType = tmp[1];
            namespaces = (tmp[2] || "").split(".").sort();

            // Unbind all events (on this namespace, if provided) for the element
            if (!type) {
                for (type in events) {
                    jQuery.event.remove(elem, type + types[t], handler, selector, true);
                }
                continue;
            }

            special = jQuery.event.special[type] || {};
            type = (selector ? special.delegateType : special.bindType) || type;
            handlers = events[type] || [];
            tmp = tmp[2] && new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)");

            // Remove matching events
            origCount = j = handlers.length;
            while (j--) {
                handleObj = handlers[j];

                if ((mappedTypes || origType === handleObj.origType) &&
                    (!handler || handler.guid === handleObj.guid) &&
                    (!tmp || tmp.test(handleObj.namespace)) &&
                    (!selector || selector === handleObj.selector || selector === "**" && handleObj.selector)) {
                    handlers.splice(j, 1);

                    if (handleObj.selector) {
                        handlers.delegateCount--;
                    }
                    if (special.remove) {
                        special.remove.call(elem, handleObj);
                    }
                }
            }

            // Remove generic event handler if we removed something and no more handlers exist
            // (avoids potential for endless recursion during removal of special event handlers)
            if (origCount && !handlers.length) {
                if (!special.teardown || special.teardown.call(elem, namespaces, elemData.handle) === false) {
                    jQuery.removeEvent(elem, type, elemData.handle);
                }

                delete events[type];
            }
        }

        // Remove the expando if it's no longer used
        if (jQuery.isEmptyObject(events)) {
            delete elemData.handle;
            data_priv.remove(elem, "events");
        }
    },

    /**
     模拟事件触发,为了让事件模型在各浏览器上表现一致 (并不推荐使用)
     * @param {Object} event 事件对象 (原生Event事件对象将被转化为jQuery.Event对象)
     * @param {Object} data 自定义传入到事件处理函数的数据
     * @param {Object} elem HTML Element元素
     * @param {Boolen} onlyHandlers 是否不冒泡 true 表示不冒泡  false表示冒泡
     */
    trigger: function(event, data, elem, onlyHandlers) {

        var i, cur, tmp, bubbleType, ontype, handle, special,
            eventPath = [elem || document],
            type = core_hasOwn.call(event, "type") ? event.type : event,
            namespaces = core_hasOwn.call(event, "namespace") ? event.namespace.split(".") : [];

        cur = tmp = elem = elem || document;

        // Don't do events on text and comment nodes
        if (elem.nodeType === 3 || elem.nodeType === 8) {
            return;
        }

        // focus/blur morphs to focusin/out; ensure we're not firing them right now
        if (rfocusMorph.test(type + jQuery.event.triggered)) {
            return;
        }

        if (type.indexOf(".") >= 0) {
            // Namespaced trigger; create a regexp to match event type in handle()
            namespaces = type.split(".");
            type = namespaces.shift();
            namespaces.sort();
        }
        ontype = type.indexOf(":") < 0 && "on" + type;

        // Caller can pass in a jQuery.Event object, Object, or just an event type string
        event = event[jQuery.expando] ?
            event :
            new jQuery.Event(type, typeof event === "object" && event);

        // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true)
        event.isTrigger = onlyHandlers ? 2 : 3;
        event.namespace = namespaces.join(".");
        event.namespace_re = event.namespace ?
            new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)") :
            null;

        // Clean up the event in case it is being reused
        event.result = undefined;
        if (!event.target) {
            event.target = elem;
        }

        // Clone any incoming data and prepend the event, creating the handler arg list
        data = data == null ?
            [event] :
            jQuery.makeArray(data, [event]);

        // Allow special events to draw outside the lines
        special = jQuery.event.special[type] || {};
        if (!onlyHandlers && special.trigger && special.trigger.apply(elem, data) === false) {
            return;
        }

        // Determine event propagation path in advance, per W3C events spec (#9951)
        // Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
        if (!onlyHandlers && !special.noBubble && !jQuery.isWindow(elem)) {

            bubbleType = special.delegateType || type;
            if (!rfocusMorph.test(bubbleType + type)) {
                cur = cur.parentNode;
            }
            for (; cur; cur = cur.parentNode) {
                eventPath.push(cur);
                tmp = cur;
            }

            // Only add window if we got to document (e.g., not plain obj or detached DOM)
            if (tmp === (elem.ownerDocument || document)) {
                eventPath.push(tmp.defaultView || tmp.parentWindow || window);
            }
        }

        // Fire handlers on the event path
        i = 0;
        while ((cur = eventPath[i++]) && !event.isPropagationStopped()) {

            event.type = i > 1 ?
                bubbleType :
            special.bindType || type;

            // jQuery handler
            handle = (data_priv.get(cur, "events") || {})[event.type] && data_priv.get(cur, "handle");
            if (handle) {
                handle.apply(cur, data);
            }

            // Native handler
            handle = ontype && cur[ontype];
            if (handle && jQuery.acceptData(cur) && handle.apply && handle.apply(cur, data) === false) {
                event.preventDefault();
            }
        }
        event.type = type;

        // If nobody prevented the default action, do it now
        if (!onlyHandlers && !event.isDefaultPrevented()) {

            if ((!special._default || special._default.apply(eventPath.pop(), data) === false) &&
                jQuery.acceptData(elem)) {

                // Call a native DOM method on the target with the same name name as the event.
                // Don't do default actions on window, that's where global variables be (#6170)
                if (ontype && jQuery.isFunction(elem[type]) && !jQuery.isWindow(elem)) {

                    // Don't re-trigger an onFOO event when we call its FOO() method
                    tmp = elem[ontype];

                    if (tmp) {
                        elem[ontype] = null;
                    }

                    // Prevent re-triggering of the same event, since we already bubbled it above
                    jQuery.event.triggered = type;
                    elem[type]();
                    jQuery.event.triggered = undefined;

                    if (tmp) {
                        elem[ontype] = tmp;
                    }
                }
            }
        }

        return event.result;
    },

    dispatch: function(event) {

        // Make a writable jQuery.Event from the native event object
        // 通过原生的事件对象创建一个可写的jQuery.Event对象
        event = jQuery.event.fix(event);

        var i, j, ret, matched, handleObj,
            handlerQueue = [],
            args = core_slice.call(arguments),
            handlers = (data_priv.get(this, "events") || {})[event.type] || [],
            special = jQuery.event.special[event.type] || {};

        // Use the fix-ed jQuery.Event rather than the (read-only) native event
        args[0] = event;
        // 事件的触发元素
        event.delegateTarget = this;

        // Call the preDispatch hook for the mapped type, and let it bail if desired
        if (special.preDispatch && special.preDispatch.call(this, event) === false) {
            return;
        }

        // Determine handlers
        handlerQueue = jQuery.event.handlers.call(this, event, handlers);

        // Run delegates first; they may want to stop propagation beneath us
        i = 0;
        // 遍历事件处理器队列{elem, handlerObjs}(取出来则对应一个包了)，且事件没有阻止冒泡
        while ((matched = handlerQueue[i++]) && !event.isPropagationStopped()) {
            event.currentTarget = matched.elem;

            j = 0;
            // 如果事件处理对象{handleObjs}存在(一个元素可能有很多handleObjs)，且事件不需要立刻阻止冒泡
            while ((handleObj = matched.handlers[j++]) && !event.isImmediatePropagationStopped()) {

                // Triggered event must either 1) have no namespace, or
                // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
                // Triggered event must either 1) have no namespace, or
                // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
                // 触发的事件必须满足其一：
                // 1) 没有命名空间
                // 2) 有命名空间，且被绑定的事件是命名空间的一个子集
                if (!event.namespace_re || event.namespace_re.test(handleObj.namespace)) {

                    event.handleObj = handleObj;
                    event.data = handleObj.data;

                    // 尝试通过特殊事件获取处理函数，否则使用handleObj中保存的handler(所以handleObj中还保存有handler(事件处理函数))
                    // handleObj.origType 定义的事件类型
                    // handleObj.handler 事件处理函数
                    // 终于到这里了，开始执行事件处理函数
                    ret = ((jQuery.event.special[handleObj.origType] || {}).handle || handleObj.handler)
                        .apply(matched.elem, args);

                    // 检测是否有返回值存在
                    if (ret !== undefined) {
                        // 如果处理函数返回值是false，则阻止冒泡，阻止默认动作
                        if ((event.result = ret) === false) {
                            event.preventDefault();
                            event.stopPropagation();
                        }
                    }
                }
            }
        }

        // Call the postDispatch hook for the mapped type
        if (special.postDispatch) {
            special.postDispatch.call(this, event);
        }

        return event.result;
    },

    /*
     处理 事件处理器 针对事件委托和原生事件（例如"click"）绑定 区分对待
     事件委托从队列头部推入，而普通事件绑定从尾部推入，通过记录delegateCount来划分，委托(delegate)绑定和普通绑定。
     * @param {Object} event:jQuery.Event事件对象
     * @param {Object} handlers ：事件处理程序
     * @return {Object} 返回事件处理器 队列
     */
    handlers: function(event, handlers) {
        var i, matches, sel, handleObj,
            handlerQueue = [],
            delegateCount = handlers.delegateCount,
            cur = event.target;

        // Find delegate handlers
        // Black-hole SVG <use> instance trees (#13180)
        // Avoid non-left-click bubbling in Firefox (#3861)
        // 如果有delegateCount，代表该事件是delegate类型的绑定
        // 找出所有delegate的处理函数列队
        // 火狐浏览器右键或者中键点击时，会错误地冒泡到document的click事件，并且stopPropagation也无效
        if (delegateCount && cur.nodeType && (!event.button || event.type !== "click")) {

            // 遍历元素及元素父级节点
            for (; cur !== this; cur = cur.parentNode || this) {

                // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
                //不处理元素为disabled的click事件
                if (cur.disabled !== true || event.type !== "click") {
                    // 开始组装符合要求的事件处理对象
                    matches = [];
                    for (i = 0; i < delegateCount; i++) {
                        handleObj = handlers[i];

                        // Don't conflict with Object.prototype properties (#13203)
                        // 选择器，用于过滤
                        sel = handleObj.selector + " ";

                        if (matches[sel] === undefined) {
                            // 如果matches上没有绑定该选择器数量
                            // 得出选择器数量，并赋值
                            matches[sel] = handleObj.needsContext ?
                            jQuery(sel, this).index(cur) >= 0 :
                                jQuery.find(sel, this, null, [cur]).length;
                        }
                        if (matches[sel]) {
                            matches.push(handleObj);
                        }
                    }
                    if (matches.length) {
                        handlerQueue.push({
                            elem: cur,
                            handlers: matches
                        });
                    }
                }
            }
        }

        // Add the remaining (directly-bound) handlers
        if (delegateCount < handlers.length) {
            handlerQueue.push({
                elem: this,
                handlers: handlers.slice(delegateCount)
            });
        }

        return handlerQueue;
    },

    // Includes some event props shared by KeyEvent and MouseEvent
    props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),

    fixHooks: {},

    keyHooks: {
        props: "char charCode key keyCode".split(" "),
        filter: function(event, original) {

            // Add which for key events
            if (event.which == null) {
                event.which = original.charCode != null ? original.charCode : original.keyCode;
            }

            return event;
        }
    },

    mouseHooks: {
        props: "button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
        filter: function(event, original) {
            var eventDoc, doc, body,
                button = original.button;

            // Calculate pageX/Y if missing and clientX/Y available
            if (event.pageX == null && original.clientX != null) {
                eventDoc = event.target.ownerDocument || document;
                doc = eventDoc.documentElement;
                body = eventDoc.body;

                event.pageX = original.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
                event.pageY = original.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0);
            }

            // Add which for click: 1 === left; 2 === middle; 3 === right
            // Note: button is not normalized, so don't use it
            if (!event.which && button !== undefined) {
                event.which = (button & 1 ? 1 : (button & 2 ? 3 : (button & 4 ? 2 : 0)));
            }

            return event;
        }
    },

    fix: function(event) {
        if (event[jQuery.expando]) {
            return event;
        }

        // Create a writable copy of the event object and normalize some properties
        var i, prop, copy,
            type = event.type,
            originalEvent = event,
            fixHook = this.fixHooks[type];

        if (!fixHook) {
            this.fixHooks[type] = fixHook =
                rmouseEvent.test(type) ? this.mouseHooks :
                    rkeyEvent.test(type) ? this.keyHooks : {};
        }
        copy = fixHook.props ? this.props.concat(fixHook.props) : this.props;

        event = new jQuery.Event(originalEvent);

        i = copy.length;
        while (i--) {
            prop = copy[i];
            event[prop] = originalEvent[prop];
        }

        // Support: Cordova 2.5 (WebKit) (#13255)
        // All events should have a target; Cordova deviceready doesn't
        if (!event.target) {
            event.target = document;
        }

        // Support: Safari 6.0+, Chrome < 28
        // Target should not be a text node (#504, #13143)
        if (event.target.nodeType === 3) {
            event.target = event.target.parentNode;
        }

        return fixHook.filter ? fixHook.filter(event, originalEvent) : event;
    },

    special: {
        load: {
            // Prevent triggered image.load events from bubbling to window.load
            noBubble: true
        },
        focus: {
            // Fire native event if possible so blur/focus sequence is correct
            trigger: function() {
                if (this !== safeActiveElement() && this.focus) {
                    this.focus();
                    return false;
                }
            },
            delegateType: "focusin"
        },
        blur: {
            trigger: function() {
                if (this === safeActiveElement() && this.blur) {
                    this.blur();
                    return false;
                }
            },
            delegateType: "focusout"
        },
        click: {
            // For checkbox, fire native event so checked state will be right
            trigger: function() {
                if (this.type === "checkbox" && this.click && jQuery.nodeName(this, "input")) {
                    this.click();
                    return false;
                }
            },

            // For cross-browser consistency, don't fire native .click() on links
            _default: function(event) {
                return jQuery.nodeName(event.target, "a");
            }
        },

        beforeunload: {
            postDispatch: function(event) {

                // Support: Firefox 20+
                // Firefox doesn't alert if the returnValue field is not set.
                if (event.result !== undefined) {
                    event.originalEvent.returnValue = event.result;
                }
            }
        }
    },

    simulate: function(type, elem, event, bubble) {
        // Piggyback on a donor event to simulate a different one.
        // Fake originalEvent to avoid donor's stopPropagation, but if the
        // simulated event prevents default then we do the same on the donor.
        var e = jQuery.extend(
            new jQuery.Event(),
            event, {
                type: type,
                isSimulated: true,
                originalEvent: {}
            }
        );
        if (bubble) {
            jQuery.event.trigger(e, null, elem);
        } else {
            jQuery.event.dispatch.call(elem, e);
        }
        if (e.isDefaultPrevented()) {
            event.preventDefault();
        }
    }
};








jQuery.removeEvent = function(elem, type, handle) {
    if (elem.removeEventListener) {
        elem.removeEventListener(type, handle, false);
    }
};

jQuery.Event = function(src, props) {
    // Allow instantiation without the 'new' keyword
    if (!(this instanceof jQuery.Event)) {
        return new jQuery.Event(src, props);
    }

    // Event object
    if (src && src.type) {
        this.originalEvent = src;
        this.type = src.type;

        // Events bubbling up the document may have been marked as prevented
        // by a handler lower down the tree; reflect the correct value.
        this.isDefaultPrevented = (src.defaultPrevented ||
        src.getPreventDefault && src.getPreventDefault()) ? returnTrue : returnFalse;

        // Event type
    } else {
        this.type = src;
    }

    // Put explicitly provided properties onto the event object
    if (props) {
        jQuery.extend(this, props);
    }

    // Create a timestamp if incoming event doesn't have one
    this.timeStamp = src && src.timeStamp || jQuery.now();

    // Mark it as fixed
    this[jQuery.expando] = true;
};

// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
    isDefaultPrevented: returnFalse,
    isPropagationStopped: returnFalse,
    isImmediatePropagationStopped: returnFalse,

    preventDefault: function() {
        var e = this.originalEvent;

        this.isDefaultPrevented = returnTrue;

        if (e && e.preventDefault) {
            e.preventDefault();
        }
    },
    stopPropagation: function() {
        var e = this.originalEvent;

        this.isPropagationStopped = returnTrue;

        if (e && e.stopPropagation) {
            e.stopPropagation();
        }
    },
    stopImmediatePropagation: function() {
        this.isImmediatePropagationStopped = returnTrue;
        this.stopPropagation();
    }
};

// Create mouseenter/leave events using mouseover/out and event-time checks
// Support: Chrome 15+
jQuery.each({
    mouseenter: "mouseover",
    mouseleave: "mouseout"
}, function(orig, fix) {
    jQuery.event.special[orig] = {
        delegateType: fix,
        bindType: fix,

        handle: function(event) {
            var ret,
                target = this,
                related = event.relatedTarget,
                handleObj = event.handleObj;

            // For mousenter/leave call the handler if related is outside the target.
            // NB: No relatedTarget if the mouse left/entered the browser window
            if (!related || (related !== target && !jQuery.contains(target, related))) {
                event.type = handleObj.origType;
                ret = handleObj.handler.apply(this, arguments);
                event.type = fix;
            }
            return ret;
        }
    };
});

// Create "bubbling" focus and blur events
// Support: Firefox, Chrome, Safari
if (!jQuery.support.focusinBubbles) {
    jQuery.each({
        focus: "focusin",
        blur: "focusout"
    }, function(orig, fix) {

        // Attach a single capturing handler while someone wants focusin/focusout
        var attaches = 0,
            handler = function(event) {
                jQuery.event.simulate(fix, event.target, jQuery.event.fix(event), true);
            };

        jQuery.event.special[fix] = {
            setup: function() {
                if (attaches++ === 0) {
                    document.addEventListener(orig, handler, true);
                }
            },
            teardown: function() {
                if (--attaches === 0) {
                    document.removeEventListener(orig, handler, true);
                }
            }
        };
    });
}

jQuery.fn.extend({

    on: function(types, selector, data, fn, /*INTERNAL*/ one) {
        var origFn, type;

        // Types can be a map of types/handlers
        if (typeof types === "object") {
            // ( types-Object, selector, data )
            if (typeof selector !== "string") {
                // ( types-Object, data )
                data = data || selector;
                selector = undefined;
            }
            for (type in types) {
                this.on(type, selector, data, types[type], one);
            }
            return this;
        }

        if (data == null && fn == null) {
            // ( types, fn )
            fn = selector;
            data = selector = undefined;
        } else if (fn == null) {
            if (typeof selector === "string") {
                // ( types, selector, fn )
                fn = data;
                data = undefined;
            } else {
                // ( types, data, fn )
                fn = data;
                data = selector;
                selector = undefined;
            }
        }
        if (fn === false) {
            fn = returnFalse;
        } else if (!fn) {
            return this;
        }

        if (one === 1) {
            origFn = fn;
            fn = function(event) {
                // Can use an empty set, since event contains the info
                jQuery().off(event);
                return origFn.apply(this, arguments);
            };
            // Use same guid so caller can remove using origFn
            fn.guid = origFn.guid || (origFn.guid = jQuery.guid++);
        }
        return this.each(function() {
            jQuery.event.add(this, types, fn, data, selector);
        });
    },
    one: function(types, selector, data, fn) {
        return this.on(types, selector, data, fn, 1);
    },
    off: function(types, selector, fn) {
        var handleObj, type;
        if (types && types.preventDefault && types.handleObj) {
            // ( event )  dispatched jQuery.Event
            handleObj = types.handleObj;
            jQuery(types.delegateTarget).off(
                handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
                handleObj.selector,
                handleObj.handler
            );
            return this;
        }
        if (typeof types === "object") {
            // ( types-object [, selector] )
            for (type in types) {
                this.off(type, selector, types[type]);
            }
            return this;
        }
        if (selector === false || typeof selector === "function") {
            // ( types [, fn] )
            fn = selector;
            selector = undefined;
        }
        if (fn === false) {
            fn = returnFalse;
        }
        return this.each(function() {
            jQuery.event.remove(this, types, fn, selector);
        });
    },

    trigger: function(type, data) {
        return this.each(function() {
            jQuery.event.trigger(type, data, this);
        });
    },
    triggerHandler: function(type, data) {
        var elem = this[0];
        if (elem) {
            return jQuery.event.trigger(type, data, elem, true);
        }
    }
});
